package client;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author daxue0929
 * @date 2023/2/16
 */

public class HelloWorldConmuser {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        HelloWorldConmuser helloWorldConmuser = new HelloWorldConmuser();
        helloWorldConmuser.receiveMessage();

    }

    private void receiveMessage() throws IOException, TimeoutException, InterruptedException {
        //1. 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //2. 设置参数
        factory.setHost("101.42.26.40");
        factory.setPort(5672);
        factory.setVirtualHost("/itcast");
        factory.setUsername("admin");
        factory.setPassword("admin");
        //3. 创建连接
        Connection connection = factory.newConnection();
        //4. 创建channel
        Channel channel = connection.createChannel();
        //5. 创建队列
        //如果没有一个名字为hello_world的队列会创建这个队列，如果有则不会创建。
        channel.queueDeclare("hello_world", true, false, false, null);

        DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
            /**
             * 当受到方法后会自动执行此方法
             * @param consumerTag 标识
             * @param envelope 获取一些信息、交换机、路由key...
             * @param properties 配置的信息
             * @param body 数据
             */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("consumerTag: " + consumerTag);
                System.out.println("Exchange: " + envelope.getExchange());
                System.out.println("Router Key: " + envelope.getRoutingKey());
                System.out.println("properties: " + properties);
                System.out.println("body: " + new String(body));
                System.out.println("---------------------------------------------------------");
                super.handleDelivery(consumerTag, envelope, properties, body);
            }
        };

        /**
         * basicConsume(String queue, boolean autoAck, Consumer callback)
         * queue: 队列名
         * autoAck: 自动确认
         * callback: 回调函数
         */
        channel.basicConsume("hello_world", true, defaultConsumer);


        // 不能关闭连接
//        channel.close();
//        connection.close();
    }
}
